import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../model/book.dart';
import '../service/book_provider.dart';

class AddBookScreen extends StatefulWidget {
  final String? isbn;

  AddBookScreen({this.isbn});

  @override
  _AddBookScreenState createState() => _AddBookScreenState();
}

class _AddBookScreenState extends State<AddBookScreen> {
  final _formKey = GlobalKey<FormState>();
  late Book _book;
  bool _isLoading = false;
  bool _autoFetched = false;

  final TextEditingController _isbnController = TextEditingController();
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _authorController = TextEditingController();
  final TextEditingController _publisherController = TextEditingController();
  final TextEditingController _publishDateController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();
  final TextEditingController _pageCountController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _book = Book(
      isbn: widget.isbn ?? '',
      title: '',
      author: '',
      addedDate: DateTime.now().toString(),
    );

    if (widget.isbn != null) {
      _isbnController.text = widget.isbn!;
      _fetchBookInfo(widget.isbn!);
    }
  }

  Future<void> _fetchBookInfo(String isbn) async {
    setState(() {
      _isLoading = true;
    });

    try {
      // 使用Open Library API获取图书信息
      final response = await http.get(
        Uri.parse('https://openlibrary.org/api/books?bibkeys=ISBN:$isbn&format=json&jscmd=data'),
      );

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        final bookData = data['ISBN:$isbn'];

        if (bookData != null) {
          setState(() {
            _titleController.text = bookData['title'] ?? '';
            _authorController.text = bookData['authors'] != null
                ? bookData['authors'].map((a) => a['name']).join(', ')
                : '';
            _publisherController.text = bookData['publishers'] != null
                ? bookData['publishers'].map((p) => p['name']).join(', ')
                : '';
            _publishDateController.text = bookData['publish_date'] ?? '';
            _descriptionController.text = '';
            _pageCountController.text = bookData['number_of_pages']?.toString() ?? '';
            
            _book.coverUrl = bookData['cover'] != null
                ? bookData['cover']['medium'] ?? bookData['cover']['large']
                : null;
            
            _autoFetched = true;
          });
        }
      }
    } catch (e) {
      print('Error fetching book info: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_autoFetched ? '确认图书信息' : '添加新图书'),
      ),
      body: _isLoading
          ? Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              padding: EdgeInsets.all(16),
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    TextFormField(
                      controller: _isbnController,
                      decoration: InputDecoration(labelText: 'ISBN'),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入ISBN';
                        }
                        return null;
                      },
                      onSaved: (value) => _book.isbn = value!,
                    ),
                    TextFormField(
                      controller: _titleController,
                      decoration: InputDecoration(labelText: '书名*'),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入书名';
                        }
                        return null;
                      },
                      onSaved: (value) => _book.title = value!,
                    ),
                    TextFormField(
                      controller: _authorController,
                      decoration: InputDecoration(labelText: '作者*'),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入作者';
                        }
                        return null;
                      },
                      onSaved: (value) => _book.author = value!,
                    ),
                    TextFormField(
                      controller: _publisherController,
                      decoration: InputDecoration(labelText: '出版社'),
                      onSaved: (value) => _book.publisher = value,
                    ),
                    TextFormField(
                      controller: _publishDateController,
                      decoration: InputDecoration(labelText: '出版日期'),
                      onSaved: (value) {
                        if (value != null && value.isNotEmpty) {
                          //_book.publishDate = DateTime.tryParse(value);
                          _book.publishDate = value;
                        }
                      },
                    ),
                    TextFormField(
                      controller: _descriptionController,
                      decoration: InputDecoration(labelText: '简介'),
                      maxLines: 3,
                      onSaved: (value) => _book.description = value,
                    ),
                    TextFormField(
                      controller: _pageCountController,
                      decoration: InputDecoration(labelText: '页数'),
                      keyboardType: TextInputType.number,
                      onSaved: (value) {
                        if (value != null && value.isNotEmpty) {
                          _book.pageCount = int.tryParse(value);
                        }
                      },
                    ),
                    SizedBox(height: 20),
                    if (_book.coverUrl != null)
                      Image.network(_book.coverUrl!, height: 150),
                    SizedBox(height: 20),
                    ElevatedButton(
                      onPressed: _submitForm,
                      child: Text('保存'),
                    ),
                  ],
                ),
              ),
            ),
    );
  }

  void _submitForm() async {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      
      try {
        setState(() {
          _isLoading = true;
        });
        
        final bookProvider = Provider.of<BookProvider>(context, listen: false);
        await bookProvider.addBook(_book);
        
        Navigator.pop(context);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('图书添加成功')),
        );
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('添加失败: $e')),
        );
      } finally {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  void dispose() {
    _isbnController.dispose();
    _titleController.dispose();
    _authorController.dispose();
    _publisherController.dispose();
    _publishDateController.dispose();
    _descriptionController.dispose();
    _pageCountController.dispose();
    super.dispose();
  }
}